require 'common'

class Site < ActiveRecord::Base

  belongs_to :program
  has_many :groups
  has_many :users
  belongs_to :package
  has_many :routesite
  has_many :routes, :through => :routesite

  validates_presence_of :name

  after_save :update_caches_for_program
  after_destroy :update_caches_for_program
  after_update :update_caches_for_program
  
  def percent_complete
    return calc_percent_complete(distance_cache, goal_cache)
  end

  def update_caches!
    distance = 0
    sessions = 0
    goal     = 0
    runners  = 0
    groups.each do |group|
      distance = distance + group.distance_cache
      sessions = sessions + group.sessions_cache
      goal     = goal     + group.goal_cache
      runners  = runners  + group.runners_cache
    end
    self.distance_cache = distance
    self.sessions_cache = sessions
    self.goal_cache     = goal
    self.runners_cache  = runners
    self.groups_cache   = groups.count
    self.save!
    logger.debug{">>> UPDATED CACHES FOR SITE: #{name}"}
  end

  def routes
	  Routesite.siteRoutes(self)
  end

  private

    def update_caches_for_program
      program.update_caches!
    end

end
